package com.unsky.utils.jpasql;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Content;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings("unchecked")
public class XmlRead {
	private static XmlRead xmlRead = new XmlRead();
	private  Map<String, XmlElement> xmlMap = new HashMap<String, XmlElement>();
	private Logger log = LoggerFactory.getLogger(XmlRead.class);
	private XmlRead() {
		try {
			read();
		} catch (JDOMException e) {
			e.printStackTrace();
			log.info(e.getMessage());
		}catch( IOException e){
			e.printStackTrace();
			log.info(e.getMessage());
		}
	}

	public static XmlRead getInstance() {
		return xmlRead;
	}


	/**
	 * 读取XML
	 * 
	 * @throws FileNotFoundException
	 * @throws JDOMException
	 * @throws IOException
	 */
	public void read() throws FileNotFoundException, JDOMException, IOException {
		SAXBuilder builder = new SAXBuilder();
		File f = new File(JPAQueryUtil.class.getResource("/sqls").getFile());
		for (File file : f.listFiles()) {
			if (!file.isDirectory()) {
				Document doc;
				doc = builder.build(new FileInputStream(file));
				// 获得文档对象
				Element root = doc.getRootElement();// 获得根节点
				List<Element> list = root.getChildren();
				for (Element e : list) {
					xmlMap.put(e.getAttributeValue("id"), 
							new XmlElement(e.getAttributeValue("sqlType"), e,
									e.getAttributeValue("resultType")));
				}
			}
		}
	}

	public XmlSql getSql(String sqlId, Map<String, Object> params) throws Exception {
		XmlElement xmlEle = xmlMap.get(sqlId);
		if(xmlEle==null||xmlEle.getEle()==null){
			throw new Exception("未找到指定的sql【"+sqlId+"】");
		}
		XmlSql xmlSql=new XmlSql();
		xmlSql.setSqlType(xmlEle.getSqlType());
		xmlSql.setReturnType(xmlEle.getResultType());
		Element e = xmlEle.getEle();
		StringBuffer sql = new StringBuffer();
		List<Content> ls = e.getContent();
		for (Content Content : ls) {
			if (Content instanceof Element) {
				Element ele = (Element) Content;
				if (ele.getName().trim().toLowerCase().equals("if")) {
					doIf(sql, ele, params);
				} else if (ele.getName().trim().toLowerCase().equals("link")) {
					doLink(sql, ele, params);
				}

			} else {
				sql.append(Content.getValue().trim()).append(" ");
			}
		}
		xmlSql.setSql(sql);
		return xmlSql;
	}
	/**
	 * if 标签处理
	 * if中不能添加<link>
	 * @version 1.0 支持操作符 =和!= 操作标记# null/'' 为又操作符
	 * @version 1.1 支持多条件查询
	 * @param id
	 * @param params
	 * @return
	 * @throws Exception
	 * @Date 2016年10月28日 下午2:26:26
	 */
	private void doIf(StringBuffer sql, Element ele, Map<String, Object> params) throws Exception {
		String test = ele.getAttributeValue("test");
		if (new ConditionDeal(test, params).getResult()) {
			sql.append(ele.getValue().trim()).append(" ");
		} 
	}

	/**
	 * link标签处理
	 * 
	 * @throws Exception
	 * 
	 * @Date unsky 2016年11月1日 上午9:59:22
	 */
	private void doLink(StringBuffer sql, Element paraEle, Map<String, Object> params) throws Exception {
		String ref = paraEle.getAttributeValue("ref");
		Element sqlEle = xmlMap.get(ref).getEle();
		if (sqlEle == null) {
			throw new Exception("没有指定的链接元素!");
		}
		List<Content> ls = sqlEle.getContent();
		for (Content Content : ls) {
			if (Content instanceof Element) {
				Element ele = (Element) Content;
				if (ele.getName().trim().toLowerCase().equals("if")) {
					doIf(sql, ele, params);
				} else if (ele.getName().trim().toLowerCase().equals("link")) {
					doLink(sql, ele, params);
				}

			} else {
				sql.append(Content.getValue().trim()).append(" ");
			}
		}
	}

}
